<?php
//校内网接口
//实现了校内网提供的api接口所提供的功能,接口返回JSON形式的值
class xiaonei_api{
	private $api_key;     //api_key
	private $secret;      //secret
	private $session_key;  //接收从校内返回的session_key
	private $v;            //校内网接口协议版本
	private $method;       //api接口名即方法名
	private $server_add;   //校内接口服务器地址
	public $msgE = array();          //返回的错误信息
	
	//初始化
	public function __construct($api_key,$secret,$v='1.0'){
		$this->api_key = $api_key;
		$this->secret = $secret;
		$this->session_key = $this->filter('xn_sig_session_key');
		$this->v = $v;
		$this->server_add = 'http://api.xiaonei.com/restserver.do';
	}
	
	//过滤函数
	private function filter($input){
		$var =& $_REQUEST;
		return $input = isset($var[$input])?$var[$input]:null;
	}
	
	/*
	//校内auth接口实现,一般是用来实现站外应用的用户认证
	public function auth($method){
		$params = array();
		switch ($method){
			case 'createToken':
				break;
				
			case 'getSession':
				$authTokenArray = self::auth('createToken');
				
				if ($authTokenArray[0] && $authTokenArray[0][0]) {
					$authToken=$authTokenArray[0][0];
					$params['authToken']=$authToken;
				}else {
					return false;
				}
				break;
		}
		$method = 'xiaonei.auth.'.$method;
		return $this->post($method,$params);
	}
	*/
	
	public function users($method,$field=array(),$format='JSON'){
		$params = array();
		switch ($method){
			case 'getInfo':
				$params['uid'] = $field['uid']?$field['uid']:$this->filter('xn_sig_user');
				if($field['fileds'])
				$params['fields'] = $field['fields'];
				break;
				
			case 'getLoggedInUser':
				break;
				
			case 'isAppAdded':
				if ($field['uid'])
				$params['uid'] = $field['uid'];
				break;
		}
		$method = 'xiaonei.users.'.$method;
		return $this->post($method,$params);
	}
	
	public function friends($method,$field=array(),$format='JSON'){
		$params = array();
		switch ($method){
			case 'areFriends':
				break;
				
			case 'get':
				//发送给校内服务器的好友列表页数及单页好友个数,好友页数默认值为0,单页好友数为500
				$params['page'] = $field['page']?$field['page']:0;
				$params['count'] = $field['count']?$field['count']:500;
				break;
				
			case 'getFriends':
				//get方法的加强版,可以获取好友的更多信息,其他同get
				$params['page'] = $field['page']?$field['page']:0;
				$params['count'] = $field['count']?$field['count']:500;
				break;
				
			case 'getAppUsers':
				//此方法仅能获取500个安装一个应用的好友id列表,多于500个好友则无法获取,需要使用getAppFriends方法
				break;
				
			case 'getAppFriends':
				//此方法可以获取安装一个应用的完整好友id列表,即使大于500个好友同样适用,可返回好友id,name,headurl,tiinurl
				$params['fields'] = $field['fields']?$field['fields']:null;
				break;
		}
		$method = 'xiaonei.friends.'.$mehtod;
		return $this->post($method,$params);
	}
	
	//向校内应用服务器发送请求
	private function post($method,$params){
		$post_string = $this->creat_post($method,$params);
		if(function_exists('curl_init')){
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,$this->server_add);
			curl_setopt($ch,CURLOPT_POST,1);
			curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
			$result = curl_exec($ch);
			curl_close($ch);
		}else {
			$context =
				array('http' =>
					array('method' => 'POST',
							'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n".
										'User-Agent: Facebook API PHP5 Client 1.1 (non-curl) '.phpversion()."\r\n".
										'Content-length: ' . strlen($post_string),
							'content' => $post_string));
			$contextid=stream_context_create($context);

			$sock=fopen($this->server_add, 'r', false, $contextid);
			if ($sock) {
				$result='';
				while (!feof($sock))
				$result.=fgets($sock, 4096);
				fclose($sock);
			}
		}
		$result = json_decode($result,true);
		if ($result['error_code'][0]) {
			$this->msgE['erroe_code'] = $result['error_code'][0];
		}
		if ($result['error_msg']) {
			$this->msgE['error_msg'] = $result['error_msg'][0];
		}
		if($this->msgE){
			foreach ($this->msgE as $msg){
				echo $msg.'<br/>';
			}
			exit;
		}
	}
	
	//创建标准格式的请求信息
	private function creat_post($method,$params){
		$params['method'] = $method;
		$params['session_key'] = $this->session_key;
		$params['api_key'] = $this->api_key;
		$params['call_id'] = microtime(true);
		if ($params['call_id'] <= $this->last_call_id) {
			$params['call_id'] = $this->last_call_id + 0.001;
		}
		$this->last_call_id = $params['call_id'];
		if (!isset($params['v'])) {
			$params['v'] = '1.0';
		}
		$post_params = array();
		foreach ($params as $key => &$val) {
		if (is_array($val)) $val = implode(',', $val);
			$post_params[] = $key.'='.urlencode($val);
		}
		$secret = $this->secret;
		$post_params[] = 'sig='.$this->generate_sig($params, $secret);
		return implode('&', $post_params);
	}
	
	public static function generate_sig($params_array, $secret) {
			$str = '';
			ksort($params_array);
			// Note: make sure that the signature parameter is not already included in
			// $params_array.
			foreach ($params_array as $k=>$v) {
			$str .= "$k=$v";
			}
			$str .= $secret;
			return md5($str);
	}
}